/*
 * Copyright 2011 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package it.davial.mgwt.client.activities.visit;

import it.davial.mgwt.client.ClientFactory;
import it.davial.mgwt.client.Visit;
import it.davial.mgwt.client.activities.BaseActivity;
import it.davial.mgwt.client.event.ActionEvent;
import it.davial.mgwt.client.event.ActionNames;
import it.davial.mgwt.client.service.DbServiceAsync;
import it.davial.mgwt.client.ui.widget.VisitCellList;
import it.davial.mgwt.client.ui.widget.cell.VisitCell;

import java.util.List;
import java.util.logging.Logger;

import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.Place;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.google.gwt.user.client.ui.HTML;
import com.googlecode.mgwt.dom.client.event.tap.TapEvent;
import com.googlecode.mgwt.dom.client.event.tap.TapHandler;
import com.googlecode.mgwt.ui.client.dialog.ConfirmDialog;
import com.googlecode.mgwt.ui.client.dialog.ConfirmDialog.ConfirmCallback;
import com.googlecode.mgwt.ui.client.widget.celllist.CellSelectedEvent;
import com.googlecode.mgwt.ui.client.widget.celllist.CellSelectedHandler;

/**
 * Activities are started and stopped by an ActivityManager associated with a container Widget.
 */
public class VisitActivity extends BaseActivity{
	private static final HTML TITLE = new HTML("Visite");
	private static final Logger logger = Logger.getLogger("VisitActivity");
	private VisitCell cell = new VisitCell();
	private List<Visit> visits;
/**
	 * Used to obtain views, eventBus, placeController.
	 * Alternatively, could be injected via GIN.
	 */
	private ClientFactory clientFactory;

	/**
	 * Sample property.
	 */
	
	public VisitActivity(ClientFactory clientFactory) {
		super(clientFactory.getVisitView(), "nav");
		this.clientFactory = clientFactory;
		// TODO Auto-generated constructor stub
	}

	@Override
	public void start(AcceptsOneWidget containerWidget, final EventBus eventBus) {
		logger.info("starting VisitActivity");
		final VisitView view = clientFactory.getVisitView();
		view.getBackbuttonText().setText("Home");

		view.getHeader().setCenterWidget(TITLE);

		view.getMainButtonText().setText("Nav");

	
		addHandlerRegistration(view.getBackbutton().addTapHandler(new TapHandler() {

			@Override
			public void onTap(TapEvent event) {
				ActionEvent.fire(eventBus, ActionNames.BACK);

			}
		}));

		addHandlerRegistration(view.getSearchButton().addTapHandler(new TapHandler() {
			
			@Override
			public void onTap(TapEvent event) {
				findFilteredVisits(view);
			}
		}));

		final VisitCellList list = new VisitCellList(view, clientFactory,cell);
		
		list.setCellDeleteHandler(new CellSelectedHandler() {
			
			@Override
			public void onCellSelected(final CellSelectedEvent event) {
				ConfirmDialog dialog = new ConfirmDialog("Delete","Areu u sure ?", new ConfirmCallback() {
					
					@Override
					public void onOk() {
						Visit visit = list.getModel(event.getIndex());
						removeVisit(view, visit);
					}
					
					@Override
					public void onCancel() {
						
					}
				});
				dialog.show();

			}
		});
		
		
		view.setVisitCellList(list);
	
		addHandlerRegistration(view.getEditButton().addTapHandler(new TapHandler() {

			@Override
			public void onTap(TapEvent event) {
			
				boolean edit = cell.isEdit();
				logger.info("edit=" + edit);
				cell.setEdit(!edit);
				view.setVisits(visits);
			}
		}));

		fillVisitList(view);
		containerWidget.setWidget(view.asWidget());

	}

/*	@Override
	public String mayStop() {
		return "Please hold on. This activity is stopping.";
	}
*/
	/**
	 * @see VisitView.Presenter#goTo(Place)
	 */
	private void findFilteredVisits(final VisitView view){
		view.getHeader().setCenterWidget(progressHeader);
		DbServiceAsync.Util.getInstance().getFilteredVisits(view.getSurname(), null, new AsyncCallback<List<Visit>>() {
			
			@Override
			public void onSuccess(List<Visit> result) {
				logger.info("success, result=" + result);
				visits = result;
				view.setVisits(visits);
				view.getHeader().setCenterWidget(TITLE);
				
			}
			
			@Override
			public void onFailure(Throwable caught) {
				logger.info("Error" + caught );
				view.getHeader().setCenterWidget(TITLE);
				
			}
		});
	}

	private void fillVisitList(final VisitView view){
		view.getHeader().setCenterWidget(progressHeader);
		DbServiceAsync.Util.getInstance().getAllVisits(new AsyncCallback<List<Visit>>() {
			
			@Override
			public void onSuccess(List<Visit> result) {
				logger.info("success, result=" + result);
				visits = result;
				view.setVisits(visits);
				view.getHeader().setCenterWidget(TITLE);
				
			}
			
			@Override
			public void onFailure(Throwable caught) {
				logger.info("Error" + caught );
				view.getHeader().setCenterWidget(TITLE);
				
			}
		});
	
	}

	private void removeVisit( final VisitView view,Visit visit ){
		view.getHeader().setCenterWidget(progressHeader);
		DbServiceAsync.Util.getInstance().deleteVisit(visit, new AsyncCallback<Boolean>() {
			
			@Override
			public void onSuccess(Boolean result) {
				logger.info("delete patient success = " + result);
				fillVisitList(view);
				
			}
			
			@Override
			public void onFailure(Throwable caught) {
				logger.info("delete patient failure," + caught);
							
			}
		});
	}
}
